package com.jason.java

import java.math.BigInteger

/**
 * 尾递归优化
 * @Author: Jason
 * @Date: 2017/7/23
 * @Time: 11:03
 */

class Result(var value: BigInteger = BigInteger.valueOf(1L))


/**
 * 求阶乘
 */
/*tailrec fun factorial(num : Int) :BigInteger {

    if(num == 0) return BigInteger.valueOf(1L)
    return BigInteger.valueOf(num.toLong()).times(factorial(num - 1))
}*/

tailrec fun factorial(num: Int, result: Result) {
    if(num == 0) result.value = result.value.times(BigInteger.valueOf(1L))
    else {
        result.value = result.value.times(BigInteger.valueOf(num.toLong()))
        factorial(num - 1, result)
    }
}


fun main(args: Array<String>) {
//    println(factorial(10000))
    val result = Result()
    factorial(5, result)
    println(result.value)


}